<?php


namespace App\Service;

use EchoPHP\Facades\File;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use PHPMailer\PHPMailer\PHPMailer;
use Ramsey\Uuid\Uuid;
use Exception;

class Mailer extends PHPMailer {

    /**
     * 邮件文件生成存储路径
     * @var
     */
    protected $JobsmailPath;
    /**
     * 是否快速发送邮件，默认普通邮件会排队发送，快速邮件如验证码走快速通道发送插队
     * @var bool
     */
    protected $QuickMail = false;
    protected $FlagType = 0;
    public $defaultSender = [];

    /**
     * @inheritDoc
     */
    public function __construct($exceptions = null) {
        parent::__construct($exceptions);

        $this->setLanguage('zh_cn');
        $this->CharSet = static::CHARSET_UTF8;
        $this->Encoding = static::ENCODING_BASE64;
        //设置默认发件人
        $this->defaultSender = config('app.sms.sender');

        //清除邮件头中的XMailer头，使用非空空格！！！
        $this->XMailer = ' ';
    }

    /**
     * 使用无忧邮件发送器（实际就是生成邮件文件，另外的发送程序进行发送）
     * @param bool $quickMail
     * @throws \Exception
     */
    public function isJobsmail(bool $quickMail = false) {
        $this->Mailer = 'jobsmail';
        $this->QuickMail = $quickMail;
        $this->JobsmailPath = config('mail.mailpath', '');
        $this->JobsmailPath = rtrim($this->JobsmailPath, '/') . '/' . ($quickMail ? 'Quick' : 'Normal') . '/' . Date('Ymd');
        if (false === File::isDirectory($this->JobsmailPath) && false === File::makeDirectory($this->JobsmailPath, 0777, true, true)) {
            throw new PHPMailerException('未能生成邮件文件存储路径[' . $this->JobsmailPath . ']');
        }
    }

    /**
     * JobsMail邮件发送逻辑
     * @param $header
     * @param $body
     * @return bool
     * @throws Exception
     */
    public function jobsmailSend($header, $body) {
        if ($this->JobsmailPath == '' || $this->JobsmailPath == '/') {
            throw new PHPMailerException('邮件文件存储路径未定义');
        }


        if ($this->SingleTo) {
            foreach ($this->SingleToArray as $toAddr) {
                $content = 'To: ' . $toAddr . "\r\n" . $header . $body;
                $mailName = $this->FlagType . '_' . $this->getUuid() . '.mail';
                $result = File::put($this->JobsmailPath . '/' . $mailName, $content);
                $this->doCallback(
                    ($result > 0),
                    [$toAddr],
                    $this->cc,
                    $this->bcc,
                    $this->Subject,
                    $body,
                    $this->From,
                    []
                );
                if ($result === false || $result <= 0) {
                    throw new PHPMailerException($this->lang('文件文件写入失败'), self::STOP_CRITICAL);
                }
            }
        } else {
            $content = $header . $body;
            $mailName = $this->FlagType . '_' . $this->getUuid() . '.mail';
            $result = File::put($this->JobsmailPath . '/' . $mailName, $content);
            $this->doCallback(
                ($result > 0),
                $this->to,
                $this->cc,
                $this->bcc,
                $this->Subject,
                $body,
                $this->From,
                []
            );
            if ($result === false || $result <= 0) {
                throw new PHPMailerException($this->lang('文件文件写入失败'), self::STOP_CRITICAL);
            }
        }

        return true;
    }

    /**
     * 获取一个UUID
     * @return string
     */
    public function getUuid() {
        try {
            return Uuid::uuid1()->toString();
        } catch (Exception $e) {
            return $this->generateId();
        }
    }

    /**
     * 添加邮件标记
     * @param $flag
     */
    public function setJobsmailFlag($flag) {
        $this->FlagType = $flag;
        $this->addCustomHeader('X-51JOB-FLAG', 'RPO' . ($this->QuickMail ? 'Realtime_' : '_') . date('Ymd') . '_' . $flag);
    }

}